package com.css.zfzx.sjcj.modules.yhdisaster.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.sjcj.common.utils.PinyinUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.yhdisaster.params.ExportDisasterEvaluateParams;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.YhDisasterNativeRepository;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.YhDisasterEntity;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.DisasterEvaluateVO;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.RpheqVo;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.YhDisasterQueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lxg
 * @date 2020-11-10
 */
@Repository
public class YhDisasterNativeRepositoryImpl<T> implements YhDisasterNativeRepository<T> {

    private static final Logger log = LoggerFactory.getLogger(YhDisasterNativeRepositoryImpl.class);

    @PersistenceContext
    @Qualifier("postgresqlEntityManager")
    private EntityManager em;
    @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}")
    private int BATCH_SIZE;
    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;

    private final DivisionRepository divisionRepository;
    private final PlatformTransactionManager transactionManager;

    @Autowired
    public YhDisasterNativeRepositoryImpl(DivisionRepository divisionRepository,
                                          PlatformTransactionManager transactionManager) {
        this.divisionRepository = divisionRepository;
        this.transactionManager = transactionManager;
    }

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchUpdate(Iterable<S> var1) {
        //TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            Iterator<S> iterator = var1.iterator();
            int index = 0;
            while (iterator.hasNext()) {
                em.merge(iterator.next());
                index++;
                if (index % BATCH_SIZE == 0) {
                    System.out.println(index);
                    em.flush();
                    em.clear();
                    System.out.println("flush end");
                }
            }
            if (index % BATCH_SIZE != 0) {
                em.flush();
                em.clear();
            }
            //transactionManager.commit(transaction);
        } catch (Exception e) {
            //transactionManager.rollback(transaction);
            e.printStackTrace();
        }
        return var1;
    }

    /**
     * 获取各省表的后缀
     */
    private String buildProvinceSubfix(String province) {
        String pinyinOfProvince = "";
        if (org.apache.commons.lang.StringUtils.isNotBlank(province)) {
            pinyinOfProvince = PinyinUtil.getPinyin(province);
            if ("山西省".equals(province)) {
                pinyinOfProvince = (pinyinOfProvince + "1");
            }
            pinyinOfProvince = ("_" + pinyinOfProvince);
        }
        return pinyinOfProvince;
    }

    @Override
    public Page<YhDisasterEntity> queryYhDisasters(YhDisasterQueryParams queryParams, int curPage, int pageSize, String type, String sort, String order) {
        String provinceSubfix = buildProvinceSubfix(queryParams.getProvince());
        StringBuilder sql = new StringBuilder("select * from yh_disaster" + provinceSubfix);
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhCode())) {
            whereSql.append(" and yh_code like :yhCode");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhUnit())) {
            whereSql.append(" and yh_unit like :yhUnit");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectName())) {
            whereSql.append(" and yh_project_name like :yhProjectName");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectTask())) {
            whereSql.append(" and yh_project_task like :yhProjectTask");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhConstructionScale())) {
            whereSql.append(" and yh_construction_scale like :yhConstructionScale");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhEarthFortification())) {
            whereSql.append(" and yh_earth_fortification = :yhEarthfortification");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhFieldType())) {
            whereSql.append(" and yh_field_type = :yhFieldType");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhLotType())) {
            whereSql.append(" and yh_lot_type = :yhLotType");
        }
        if (!StringUtils.isEmpty(queryParams.getExtends1())) {
            whereSql.append(" and extends1 = :extends1");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getEvaluationResult())) {
            if ("未评估".equals(queryParams.getEvaluationResult())) {
                whereSql.append(" and evaluation_result is null");
            } else {
                whereSql.append(" and evaluation_result = :evaluationResult");
            }
        }
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);
        if (!containtRole) {
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user_id =:userId");
            }
            if (containtRolePro) {
                whereSql.append(" and province like :authprovince");
            }
            if (containtRoleCity) {
                whereSql.append(" and city like :authcity");
            }
            if (containtRoleArea) {
                whereSql.append(" and area like :autharea");
            }
        }
        whereSql.append(" and yh_project_type = :type");
        whereSql.append(" and is_valid = 1");
        whereSql.append(" and quality_result =1");
        if (!PlatformObjectUtils.isEmpty(sort)) {
            whereSql.append(" order by ").append(sort).append(" ").append(order);
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), YhDisasterEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from yh_disaster" + provinceSubfix);
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhCode())) {
            query.setParameter("yhCode", "%" + queryParams.getYhCode() + "%");
            countQuery.setParameter("yhCode", "%" + queryParams.getYhCode() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhUnit())) {
            query.setParameter("yhUnit", "%" + queryParams.getYhUnit() + "%");
            countQuery.setParameter("yhUnit", "%" + queryParams.getYhUnit() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectName())) {
            query.setParameter("yhProjectName", "%" + queryParams.getYhProjectName() + "%");
            countQuery.setParameter("yhProjectName", "%" + queryParams.getYhProjectName() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectTask())) {
            query.setParameter("yhProjectTask", "%" + queryParams.getYhProjectTask() + "%");
            countQuery.setParameter("yhProjectTask", "%" + queryParams.getYhProjectTask() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
            countQuery.setParameter("province", queryParams.getProvince());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
            countQuery.setParameter("city", queryParams.getCity());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());
            countQuery.setParameter("area", queryParams.getArea());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhConstructionScale())) {
            query.setParameter("yhConstructionScale", "%" + queryParams.getYhConstructionScale() + "%");
            countQuery.setParameter("yhConstructionScale", "%" + queryParams.getYhConstructionScale() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhEarthFortification())) {
            query.setParameter("yhEarthfortification", queryParams.getYhEarthFortification());
            countQuery.setParameter("yhEarthfortification", queryParams.getYhEarthFortification());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhFieldType())) {
            query.setParameter("yhFieldType", queryParams.getYhFieldType());
            countQuery.setParameter("yhFieldType", queryParams.getYhFieldType());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhLotType())) {
            query.setParameter("yhLotType", queryParams.getYhLotType());
            countQuery.setParameter("yhLotType", queryParams.getYhLotType());
        }
        if (!StringUtils.isEmpty(queryParams.getExtends1())) {
            query.setParameter("extends1", queryParams.getExtends1());
            countQuery.setParameter("extends1", queryParams.getExtends1());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getEvaluationResult())) {
            if (!"未评估".equals(queryParams.getEvaluationResult())) {
                query.setParameter("evaluationResult", queryParams.getEvaluationResult());
                countQuery.setParameter("evaluationResult", queryParams.getEvaluationResult());
            }
        }
        if (!containtRole) {
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                query.setParameter("userId", PlatformSessionUtils.getUserId());
                countQuery.setParameter("userId", PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = "";
            if (validDivisionById != null) {
                divisionName = validDivisionById.getDivisionName();
            }
            if (containtRolePro) {
                query.setParameter("authprovince", "%" + divisionName + "%");
                countQuery.setParameter("authprovince", "%" + divisionName + "%");
            }
            if (containtRoleCity) {
                query.setParameter("authcity", "%" + divisionName + "%");
                countQuery.setParameter("authcity", "%" + divisionName + "%");
            }
            if (containtRoleArea) {
                query.setParameter("autharea", "%" + divisionName + "%");
                countQuery.setParameter("autharea", "%" + divisionName + "%");
            }
        }
        query.setParameter("type", type);
        countQuery.setParameter("type", type);
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<YhDisasterEntity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        return new PageImpl<>(list, pageable, count.longValue());
    }

    @Override
    public List<YhDisasterEntity> exportYhDisasters(YhDisasterQueryParams queryParams, String type) {
        String provinceSubfix = buildProvinceSubfix(queryParams.getProvince());
        StringBuilder sql = new StringBuilder("select * from yh_disaster" + provinceSubfix);
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhCode())) {
            whereSql.append(" and yh_code like :yhCode");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhUnit())) {
            whereSql.append(" and yh_unit like :yhUnit");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectName())) {
            whereSql.append(" and yh_project_name like :yhProjectName");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectTask())) {
            whereSql.append(" and yh_project_task like :yhProjectTask");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhConstructionScale())) {
            whereSql.append(" and yh_construction_scale like :yhConstructionScale");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhEarthFortification())) {
            whereSql.append(" and yh_earth_fortification = :yhEarthfortification");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhFieldType())) {
            whereSql.append(" and yh_field_type = :yhFieldType");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhLotType())) {
            whereSql.append(" and yh_lot_type = :yhLotType");
        }
        if (!StringUtils.isEmpty(queryParams.getExtends1())) {
            whereSql.append(" and extends1 = :extends1");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getEvaluationResult())) {
            if ("未评估".equals(queryParams.getEvaluationResult())) {
                whereSql.append(" and evaluation_result is null");
            } else {
                whereSql.append(" and evaluation_result = :evaluationResult");
            }
        }
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);
        if (!containtRole) {
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user_id =:userId");
            }
            if (containtRolePro) {
                whereSql.append(" and province like :authProvince");
            }
            if (containtRoleCity) {
                whereSql.append(" and city like :authCity");
            }
            if (containtRoleArea) {
                whereSql.append(" and area like :authArea");
            }
        }
        whereSql.append(" and yh_project_type = :type");
        whereSql.append(" and is_valid = 1");
        whereSql.append(" and quality_result =1");
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), YhDisasterEntity.class);
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhCode())) {
            query.setParameter("yhCode", "%" + queryParams.getYhCode() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhUnit())) {
            query.setParameter("yhUnit", "%" + queryParams.getYhUnit() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectName())) {
            query.setParameter("yhProjectName", "%" + queryParams.getYhProjectName() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhProjectTask())) {
            query.setParameter("yhProjectTask", "%" + queryParams.getYhProjectTask() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());

        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhConstructionScale())) {
            query.setParameter("yhConstructionScale", "%" + queryParams.getYhConstructionScale() + "%");

        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhEarthFortification())) {
            query.setParameter("yhEarthfortification", queryParams.getYhEarthFortification());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhFieldType())) {
            query.setParameter("yhFieldType", queryParams.getYhFieldType());

        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYhLotType())) {
            query.setParameter("yhLotType", queryParams.getYhLotType());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getEvaluationResult())) {
            if (!"未评估".equals(queryParams.getEvaluationResult())) {
                query.setParameter("evaluationResult", queryParams.getEvaluationResult());
            }
        }
        if (!StringUtils.isEmpty(queryParams.getExtends1())) {
            query.setParameter("extends1", queryParams.getExtends1());
        }
        if (!containtRole) {
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                query.setParameter("userId", PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = validDivisionById.getDivisionName();
            if (containtRolePro) {
                query.setParameter("authProvince", "%" + divisionName + "%");
            }
            if (containtRoleCity) {
                query.setParameter("authCity", "%" + divisionName + "%");
            }
            if (containtRoleArea) {
                query.setParameter("authArea", "%" + divisionName + "%");
            }
        }
        query.setParameter("type", type);
        return (List<YhDisasterEntity>) query.getResultList();
    }

    @Override
    public List<YhDisasterEntity> queryRpheq(RpheqVo rpheqVo) {
        StringBuilder sql = new StringBuilder("select * from yh_disaster ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");

        if (!PlatformObjectUtils.isEmpty(rpheqVo.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getArea())) {
            whereSql.append(" and area = :area");
        }
//        String userId = PlatformSessionUtils.getUserId();
//        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
//        //是否为超级管理员
//        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
//        //是否为省级管理员
//        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
//        //是否为市级管理员
//        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
//        //是否为县级管理员
//        boolean containtRoleArea=ServerUtil.isContaintRole(roles,areaCode);
//        if(!containtRole){
//            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
//                whereSql.append(" and create_user_id =:userId");
//            }
//            if(containtRolePro){
//                whereSql.append(" and province like :province");
//            }
//            if(containtRoleCity){
//                whereSql.append(" and city like :city");
//            }
//            if(containtRoleArea){
//                whereSql.append(" and area like :area");
//            }
//        }
//        whereSql.append(" and yh_project_type = :type");
        whereSql.append(" and is_valid = 1");
        whereSql.append(" and quality_result =1");
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), YhDisasterEntity.class);
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getProvince())) {
            query.setParameter("province", rpheqVo.getProvince());
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getCity())) {
            query.setParameter("city", rpheqVo.getCity());
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getArea())) {
            query.setParameter("area", rpheqVo.getArea());

        }
//        if(!containtRole){
//            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
//                query.setParameter("userId",PlatformSessionUtils.getUserId());
//            }
//            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
//            String divisionId = mainDept.getDivisionId();
//            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
//            String divisionName = validDivisionById.getDivisionName();
//            if(containtRolePro){
//                query.setParameter("province","%"+divisionName+"%");
//            }
//            if(containtRoleCity){
//                query.setParameter("city","%"+divisionName+"%");
//            }
//            if(containtRoleArea){
//                query.setParameter("area","%"+divisionName+"%");
//            }
//        }
//        query.setParameter("type",type);
        return (List<YhDisasterEntity>) query.getResultList();
    }

    @Override
    public List<YhDisasterEntity> queryRpheqByProjectType(RpheqVo rpheqVo, int i) {
        String provinceSubfix = buildProvinceSubfix(rpheqVo.getProvince());
        String bearDisasterBodyType = rpheqVo.getBearDisasterBodyType();//承灾体类别
        //2.判断承灾体类别
        //承灾体类别 建筑类：bt 构筑物类：st  生命线：lt
        if ("山东省".equals(rpheqVo.getProvince())) {
            provinceSubfix=provinceSubfix+"_01";
        }
        if ("山东省".equals(rpheqVo.getProvince())) {
            if ("F".equals(bearDisasterBodyType)) {
                provinceSubfix = provinceSubfix + "_13_01";
            }else if ("G".equals(bearDisasterBodyType)) {
                provinceSubfix = provinceSubfix + "_13";
            }else if ("D".equals(bearDisasterBodyType)) {
                String city = rpheqVo.getCity();
                if ("济南市".equals(city) || "青岛市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_1";
                } else if ("潍坊市".equals(city) || "淄博市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_2";
                } else if ("聊城市".equals(city) || "枣庄市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_3";
                } else if ("菏泽市".equals(city) || "东营市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_4";
                } else if ("滨州市".equals(city) || "烟台市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_5";
                } else if ("泰安市".equals(city) || "济宁市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_6";
                } else if ("威海市".equals(city) || "德州市".equals(city) || "日照市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_7";
                } else if ("临沂市".equals(city)) {
                    provinceSubfix = provinceSubfix + "_8";
                }
            } else {
                switch (bearDisasterBodyType) {
                    case "A":
                    case "B":
                        provinceSubfix = provinceSubfix + "_11";
                        break;
                    case "C":
                    case "E":
                        provinceSubfix = provinceSubfix + "_12";
                        break;
                }
            }
        }
        StringBuilder sql = new StringBuilder("select * from yh_disaster" + provinceSubfix);
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");

        if (!PlatformObjectUtils.isEmpty(rpheqVo.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getArea())) {
            whereSql.append(" and area = :area");
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getProjectTypes())) {
            whereSql.append(" and yh_project_type in :projectTypes");
        }
        switch (bearDisasterBodyType) {
            case "A":
                whereSql.append(" and extends1 ='A'");
                break;
            case "B":
                whereSql.append(" and extends1 ='B'");
                break;
            case "C":
                whereSql.append(" and extends1 ='C'");
                break;
            case "D":
                whereSql.append(" and extends1 ='D'");
                break;
            case "E":
                whereSql.append(" and extends1 ='E'");
                break;
            case "F":
                whereSql.append(" and extends1 ='F'");
                break;
            case "G":
                whereSql.append(" and extends1 ='G'");
                break;
        }
        if (!StringUtils.isEmpty(rpheqVo.getSign())) {
            if ("1".equals(rpheqVo.getSign())) {
                whereSql.append(" and extends1 in ('A','B')");
            } else if ("2".equals(rpheqVo.getSign())) {
                whereSql.append(" and extends1 in ('C','D','E')");
            }
        }
        whereSql.append(" and is_valid = 1");
        whereSql.append(" and quality_result =1");
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), YhDisasterEntity.class);

        if (!PlatformObjectUtils.isEmpty(rpheqVo.getProvince())) {
            query.setParameter("province", rpheqVo.getProvince());
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getCity())) {
            query.setParameter("city", rpheqVo.getCity());
        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getArea())) {
            query.setParameter("area", rpheqVo.getArea());

        }
        if (!PlatformObjectUtils.isEmpty(rpheqVo.getProjectTypes())) {
            query.setParameter("projectTypes", rpheqVo.getProjectTypes());
        }

        return (List<YhDisasterEntity>) query.getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Object> queryDisasterEvaluate(ExportDisasterEvaluateParams params, int pages) {
        if (pages > 0) {
            int batchSize = 10000;
            params.setPageStart((pages - 1) * batchSize);
            params.setPageEnd(batchSize);
        }
        String provinceSubfix = buildProvinceSubfix(params.getProvince());
        StringBuilder sql = new StringBuilder();
        sql.append("select yh_code yhCode, yh_project_type yhProjectType, yh_earth_intensity yhEarthIntensity,")
                .append(" yh_now_earth_qh yhNowEarthQh, evaluation_result evaluationResult,")
                .append(" is_up_to_standard isUpToStandard, rvalue rvalue, cvalue cvalue, vvalue vvalue,")
                .append(" pheq pheq, extends1 liveBuildType from yh_disaster" + provinceSubfix)
                .append(" where is_valid = '1'")
        ;
        if (params.isYhCodeNotEmpty()) // 编号
            sql.append(" and yh_code like :yhCode");
        if (params.isYhProjectTypeNotEmpty()) // 工程类别
            sql.append(" and yh_project_type = :yhProjectType");
        if (params.isYhUnitNotEmpty()) // 单位（小区）
            sql.append(" and yh_unit = :yh_unit");
        if (params.isProvinceNotEmpty()) // 省
            sql.append(" and province = :province");
        if (params.isCityNotEmpty()) // 地市
            sql.append(" and city = :city");
        if (params.isAreaNotEmpty()) // 区县
            sql.append(" and area = :area");
        if (params.isYhConstructionScaleNotEmpty()) // 建设规模
            sql.append(" and yh_construction_scale = :yhConstructionScale");
        if (params.isYhEarthFortificationNotEmpty()) // 抗震设防类别
            sql.append(" and yh_earth_intensity = :yhEarthIntensity");
        if (params.isYhFieldTypeNotEmpty()) // 场地类别
            sql.append(" and yh_field_type = :yhFieldType");
        if (params.isEvaluationResultNotEmpty()) // 评估结果
            sql.append(" and evaluation_result = :evaluationResult");
        if (params.isLiveBuildTypeNotEmpty())
            sql.append(" and extends1 = :liveBuildType");
        if (params.getPageStart() != null && params.getPageEnd() != null)
            sql.append(" limit :pageStart, :pageEnd");
        Query query = em.createNativeQuery(sql.toString());
        if (params.isYhCodeNotEmpty()) // 编号
            query.setParameter("yhCode", "%" + params.getYhCode() + "%");
        if (params.isYhProjectTypeNotEmpty()) // 工程类别
            query.setParameter("yhProjectType", params.getYhProjectType());
        if (params.isYhUnitNotEmpty()) // 单位（小区）
            query.setParameter("yh_unit", "%" + params.getYhUnit() + "%");
        if (params.isProvinceNotEmpty()) // 省
            query.setParameter("province", params.getProvince());
        if (params.isCityNotEmpty()) // 地市
            query.setParameter("city", params.getCity());
        if (params.isAreaNotEmpty()) // 区县
            query.setParameter("area", params.getArea());
        if (params.isYhConstructionScaleNotEmpty()) // 建设规模
            query.setParameter("yhConstructionScale", params.getYhConstructionScale());
        if (params.isYhEarthFortificationNotEmpty()) // 抗震设防类别
            query.setParameter("yhEarthFortification", params.getYhEarthFortification());
        if (params.isYhFieldTypeNotEmpty()) // 场地类别
            query.setParameter("yhFieldType", params.getYhFieldType());
        if (params.isEvaluationResultNotEmpty()) // 评估结果
            query.setParameter("evaluationResult", params.getEvaluationResult());
        if (params.isLiveBuildTypeNotEmpty())
            query.setParameter("liveBuildType", params.getExtends1());
        if (params.getPageStart() != null && params.getPageEnd() != null) {
            query.setParameter("pageStart", params.getPageStart());
            query.setParameter("pageEnd", params.getPageEnd());
        }
        long queryStart = System.currentTimeMillis();
        List<Object[]> resultList = query.getResultList();
        log.info("评估结果导出查询耗时：{}", (System.currentTimeMillis() - queryStart));
        long transStart = System.currentTimeMillis();
        List<Object> resList = resultList.stream().map(DisasterEvaluateVO::new).collect(Collectors.toList());
        log.info("转化参数耗时：{}", System.currentTimeMillis() - transStart);
        return resList;
    }
}
